package org.zlb.algorithm.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * TODO
 *
 * @author zhoulingbo
 * @date 2021/7/8 11:36
 */
public class AopSortHandler implements InvocationHandler {

    private Object object;

    public AopSortHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        before(proxy, method, args);

        Object ret = method.invoke(object, args);

        after(proxy, method, args);

        return ret;
    }

    void before(Object proxy, Method method, Object[] args) {
        if (args.length > 0 && args[0] instanceof int[]) {
            int[] arr = (int[]) args[0];
            System.out.print("排序前： ");
            for (int a : arr) {
                System.out.print(a + "  ");
            }
            System.out.println();
        }
    }

    void after(Object proxy, Method method, Object[] args) {
        if (args.length > 0 && args[0] instanceof int[]) {
            int[] arr = (int[]) args[0];
            System.out.print("排序后： ");
            for (int a : arr) {
                System.out.print(a + "  ");
            }
            System.out.println();
            int cur = arr[0];
            boolean hasError = false;
            for (int a : arr) {
                if (a < cur) {
                    System.out.println("排序错误！");
                    hasError = true;
                    break;
                }
                cur = a;
            }

            if (!hasError)
                System.out.println("排序正确！");
        }
    }
}
